package com.atguigu.eduservice.service.impl;

import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.subject.OneSubject;
import com.atguigu.eduservice.entity.subject.TwoSubject;
import com.atguigu.eduservice.mapper.SubjectMapper;
import com.atguigu.eduservice.service.SubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
* @author 34671
* @description 针对表【edu_subject(课程科目)】的数据库操作Service实现
* @createDate 2023-03-04 10:58:49
*/
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, EduSubject> implements SubjectService {
    //操作mapper，可以使用baseMapper  ServiceImpl有注入
    public List<OneSubject> getAllSubject() {
        //查询出所有的一级分类 parent_id=0
        QueryWrapper<EduSubject> oneWrapper=new QueryWrapper<>();
        oneWrapper.eq("parent_id", 0);
        List<EduSubject> oneList = baseMapper.selectList(oneWrapper);
        //查出所有的二级分类 parent_id!=0
        QueryWrapper<EduSubject> twoWrapper=new QueryWrapper<>();
         twoWrapper.ne("parent_id", 0);
        List<EduSubject> twoList = baseMapper.selectList(twoWrapper);

        //填充一级分类,需要返回的实体是OneSubject
        List<OneSubject> oList=new ArrayList<>();

        //遍历
        for (int i=0;i<oneList.size();i++) {
            EduSubject eduSubject=oneList.get(i);
            OneSubject oneSubject=new OneSubject();
//            beanUtils是复制对象的属性，不可直接集合复制
            BeanUtils.copyProperties(eduSubject,oneSubject);
            oList.add(oneSubject);

            //封装二级对象
            for(int m=0;m<twoList.size();m++) {
                EduSubject tSubject=twoList.get(m);//得到原来

                //parent_id
                //踩坑==
                //==比较地址，equals比较内容
//                if(eduSubject.getId()==tSubject.getParentId())
                if(tSubject.getParentId().equals(eduSubject.getId())) {
                    TwoSubject twoSubject=new TwoSubject();
                    BeanUtils.copyProperties(tSubject, twoSubject);
                    oList.get(i).getChildren().add(twoSubject);
                }
            }
        }
        return oList;
    }
}




